package serv

import (
	"time"
	"io/ioutil"
	"strconv"
	"bytes"
	"net/http"
	"compress/gzip"
	"rocks/util"
	"github.com/ant0ine/go-json-rest/rest"
)




type resStruct struct{
	Bytes []byte
	LM string  //Last-Modified
	CT string  //Content-Type
	CE string  //Content-Encoding

	CL int  //Content-Length
	Status int

}
func outputResStructHeader(res *resStruct,w rest.ResponseWriter)(err error){
	//w.(http.ResponseWriter).WriteHeader(res.Status)
	w.Header().Set("Content-Type",res.CT)
	w.Header().Set("Last-Modified",res.LM)
	w.Header().Set("Content-Encoding",res.CE)
	cl:=strconv.Itoa(res.CL)
	w.Header().Set("Content-Length", cl)
	return
}
func outPutTTL(ckey []byte,w rest.ResponseWriter ){
	ttl,err:=util.Ldb.TTL(ckey)
	if err==nil{
		w.Header().Set("Cache-Control","max-age="+strconv.Itoa(int(ttl)))
	}
}
func outPutAge(ckey []byte,w rest.ResponseWriter ){
	ttl,err:=util.Ldb.TTL(ckey)
	if err==nil{
		w.Header().Set("age",strconv.Itoa(int(ttl)))
	}
}
var httpClient *http.Client=http.DefaultClient
func getBackEndData(request *http.Request)(*resStruct,error) {



	response, err := httpClient.Do(request)
	if err != nil {
		return nil,err
	}
	defer response.Body.Close() // Check that the server actual sent compressed data

	res:=new(resStruct)
	res.Status= response.StatusCode
	if response.Header.Get("Last-Modified")!=""{
		res.LM=response.Header.Get("Last-Modified");
	}else{
		res.LM=time.Now().Format(time.RFC1123)
	}

	res.CT=response.Header.Get("Content-Type");
	res.CE=response.Header.Get("Content-Encoding");

	bytes,err:=ioutil.ReadAll(response.Body);

	if err==nil{
		res.Bytes=bytes
		if response.Header.Get("Content-Length")!=""{
			res.CL,_=strconv.Atoi(response.Header.Get("Content-Length"));
		}else{
			res.CL=len(res.Bytes)
		}

	}

	err=getGzipedResStruct(res)
	return res,err
}
func getGzipedResStruct(res *resStruct)(error){
	if(res.CE=="gzip"|| res.CL<1500) {
		return nil
	}

	buf:=new(bytes.Buffer)
	gwriter := gzip.NewWriter(buf)
	defer func(){
		buf.Reset()
		buf=nil
	} ()
	var  err error
	if err == nil {
		_,err2:=gwriter.Write(res.Bytes)
		gwriter.Close()

		err=err2
		if err==nil{
			res.Bytes=buf.Bytes()
			res.CL=len(res.Bytes)
			res.CE="gzip"
		}
	}
	return  err


}
